package com.story.api.moduler.user.controller;

import com.story.api.common.exception.BizExceptionEnum;
import com.story.api.common.exception.BussinessException;
import com.story.api.common.persistence.dao.AppUserMapper;
import com.story.api.common.persistence.model.AppUser;
import com.story.api.common.persistence.model.PlayRecord;
import com.story.api.common.persistence.model.SongList;
import com.story.api.common.result.ServerResponse;
import com.story.api.common.util.MsgCacheUtil;
import com.story.api.config.properties.JwtProperties;
import com.story.api.config.properties.UpyunProperties;
import com.story.api.moduler.upyun.service.UpyunService;
import com.story.api.moduler.user.constant.LoginType;
import com.story.api.moduler.user.constant.MsgType;
import com.story.api.moduler.user.controller.dto.AuthRequest;
import com.story.api.moduler.user.controller.dto.AuthResponse;
import com.story.api.moduler.user.dao.SongListDao;
import com.story.api.moduler.user.dao.UserLoginDao;
import com.story.api.moduler.user.service.MessageService;
import com.story.api.moduler.user.service.UserService;
import com.story.api.moduler.user.util.JwtTokenUtil;
import com.story.api.moduler.user.validator.MsgValidator;
import com.story.api.moduler.user.validator.impl.PhoneValidator;
import com.story.api.moduler.user.validator.impl.SocialValidator;
import com.story.core.base.controller.BaseController;
import com.story.core.util.MD5Util;
import com.story.core.util.RegExpValidatorUtil;
import com.story.core.util.UriUtil;
import com.submail.lib.MessageSend;
import main.java.com.upyun.UpException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @decription 用户相关
 * @Date 2017-12-14 17:12
 */
@RestController
@RequestMapping(value = "/child")
public class UserController extends BaseController{

    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private static final Long EXPIRE_TIME = 3600L;

    @Autowired
    private UserService userService;

    @Autowired
    private PhoneValidator phoneValidator;

    @Autowired
    private SocialValidator socialValidator;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserLoginDao userLoginDao;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private SongListDao songListDao;

    @Autowired
    private UpyunService upyunService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private MsgValidator msgValidator;

    @Autowired
    private UpyunProperties upyunProperties;

    /**
     * 注册时校验手机号
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/regCheckPhone",method = RequestMethod.POST)
    public ServerResponse regCheckPhone(@RequestParam(value = "phoneNum") String phoneNum) {
        if(!RegExpValidatorUtil.isHandset(phoneNum)) {
            return ServerResponse.getErrorMessage("手机号不符合要求");
        }
        int count = userLoginDao.existPhone(phoneNum);
        if(count >= 1) {
            return ServerResponse.getErrorMessage("账号已存在");
        }
        return ServerResponse.getSuccess("账号可用");
    }

    /**
     * 忘记密码时校验
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/forgetCheckPhone",method = RequestMethod.POST)
    public ServerResponse forgetCheckPhone(@RequestParam(value = "phoneNum") String phoneNum) {
        if(!RegExpValidatorUtil.isHandset(phoneNum)) {
            return ServerResponse.getErrorMessage("手机号不符合要求");
        }
        int count = userLoginDao.existPhone(phoneNum);
        if(count != 1) {
            return ServerResponse.getErrorMessage("账号不存在");
        }
        return ServerResponse.getSuccess("账号可用");
    }

    /**
     * 发送短信
     * @param phoneNum
     * @param msgType
     * @return
     */
    @RequestMapping(value = "/sendMsg",method = RequestMethod.POST)
    public ServerResponse sendRegMsg(@RequestParam(value = "phoneNum") String phoneNum,
                                     @RequestParam(value = "msgType") String msgType) {
        if(!RegExpValidatorUtil.isHandset(phoneNum)) {
            return ServerResponse.getErrorMessage("手机号不符合要求");
        }
        if(MsgType.REG_TYPE.getType().equals(msgType)) {
            int count = userLoginDao.existPhone(phoneNum);
            if(count >= 1) {
                return ServerResponse.getErrorMessage("该手机号已被注册");
            }
        }
        if(MsgType.FORGET_TYPE.getType().equals(msgType)) {
            int count = userLoginDao.existPhone(phoneNum);
            if(count != 1) {
                return ServerResponse.getErrorMessage("账号不存在");
            }
        }
        //1.生成随机码
        String code = String.valueOf(RandomUtils.nextInt(900000)+100000);
        //2.发送
        ServerResponse response = messageService.sendMessage(phoneNum,code);
        //3.在发送成功之后缓存随机码
        if(!response.isSuccess()) {
            return ServerResponse.getErrorMessage("发送失败");
        }
        if(MsgType.REG_TYPE.getType().equals(msgType)) {
            MsgCacheUtil.setKey(MsgType.REG_TYPE.getTypePrefix()+phoneNum,code);
        }
        if(MsgType.FORGET_TYPE.getType().equals(msgType)) {
            MsgCacheUtil.setKey(MsgType.FORGET_TYPE.getTypePrefix()+phoneNum,code);
        }
        if(MsgType.LOGIN_TYPE.getType().equals(msgType)) {
            MsgCacheUtil.setKey(MsgType.LOGIN_TYPE.getTypePrefix()+phoneNum,code);
        }

        return ServerResponse.getSuccess("发送成功");
    }

    /**
     * 短信验证
     * @param phoneNum
     * @param code
     * @param msgType
     * @return
     */
    @RequestMapping(value = "/checkPhoneCode",method = RequestMethod.POST)
    public ServerResponse checkPhoneCode(@RequestParam(value = "phoneNum") String phoneNum,
                                         @RequestParam(value = "code") String code,
                                         @RequestParam(value = "msgType") String msgType) {
        String prefix = null;
        if(MsgType.REG_TYPE.getType().equals(msgType)) {
            prefix = MsgType.REG_TYPE.getTypePrefix();
        }
        if(MsgType.FORGET_TYPE.getType().equals(msgType)) {
            prefix = MsgType.REG_TYPE.getTypePrefix();
        }
        String cacheCode = MsgCacheUtil.getKey(prefix+phoneNum);
        if(StringUtils.isBlank(cacheCode)) {
            return ServerResponse.getErrorMessage("验证码已过期");
        }
        if(code.equals(cacheCode)) {
            return ServerResponse.getSuccess("验证通过");
        } else {
           return ServerResponse.getErrorMessage("验证码错误,请重新输入");
        }
    }

    /**
     * 找回密码(修改)
     * @param phoneNum
     * @param code
     * @param password
     * @return
     */
    @RequestMapping(value = "/forgetUpPwd",method = RequestMethod.POST)
    public ServerResponse forgetForUpPwd(@RequestParam(value = "phoneNum") String phoneNum,
                                         @RequestParam(value = "code") String code,
                                         @RequestParam(value = "password") String password) {
        if(password.length() < 6 || password.length() > 20) {
            return ServerResponse.getErrorMessage("密码不符合要求");
        }
        String cacheCode = MsgCacheUtil.getKey(MsgType.FORGET_TYPE.getTypePrefix()+phoneNum);
        if(StringUtils.isBlank(cacheCode)) {
            return ServerResponse.getErrorMessage("验证码已过期");
        }
        if(!code.equals(cacheCode)) {
            return ServerResponse.getErrorMessage("验证码错误,请重新输入");
        }
        ServerResponse response = userService.updatePwd(phoneNum,password);
        if(response.isSuccess()) {
            MsgCacheUtil.delKey(MsgType.FORGET_TYPE.getTypePrefix()+phoneNum);
        }
        return response;
    }

    /**
     * 用户注册，主要是手机号，三方登录已经在认证中实现注册
     * @param phoneNum
     * @param password
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ServerResponse register(@RequestParam(value = "phoneNum") String phoneNum,
                                   @RequestParam(value = "password") String password) {
        if(StringUtils.isBlank(phoneNum)) {
            log.error("手机号为空");
            return ServerResponse.getErrorMessage("手机号不能为空");
        }
        if(!RegExpValidatorUtil.isHandset(phoneNum)) {
            log.error("手机号不符合要求");
            return ServerResponse.getErrorMessage("手机号不符合要求");
        }
        if(StringUtils.isBlank(password)) {
            log.error("密码不能为空");
            return ServerResponse.getErrorMessage("密码不能为空");
        }
        if(password.length() < 6 || password.length() > 20) {
            log.error("密码不符合要求");
            return ServerResponse.getErrorMessage("密码不能少于6位");
        }
        ServerResponse response = userService.register(phoneNum,password);
        if(!response.isSuccess()) {
            return response;
        }
        //注册成功后生成jwt返回
        final String randomKey = jwtTokenUtil.getRandomKey();
        String userId = String.valueOf(userLoginDao.getUserIdByCredential(phoneNum, MD5Util.encrypt(password), LoginType.PHONE_TYPE));
        final String token = jwtTokenUtil.generateToken(userId, randomKey);
        return ServerResponse.getSuccess("success",new AuthResponse(token,randomKey));
    }

    /**
     * 认证
     * @param credenceName
     * @param credenceCode
     * @param credenceType
     * @return
     */
    @RequestMapping(value = "${jwt.auth-path}",method = RequestMethod.POST)
    public ServerResponse auth(@RequestParam(value = "credenceName") String credenceName,
                               @RequestParam(value = "credenceCode") String credenceCode,
                               @RequestParam(value = "credenceType") String credenceType) {
        if(StringUtils.isBlank(credenceName)) {
            return ServerResponse.getErrorMessage("用户名不能为空");
        }
        if(StringUtils.isBlank(credenceCode)) {
            return ServerResponse.getErrorMessage("密码不能为空");
        }
        if(StringUtils.isBlank(credenceType)) {
            return ServerResponse.getErrorMessage("认证类型不能为空");
        }
        AuthRequest authRequest = new AuthRequest();
        authRequest.setCredenceName(credenceName);
        authRequest.setCredenceCode(credenceCode);
        authRequest.setCredenceType(credenceType);
        boolean isValidation = false;
        if("phone".equals(credenceType)) {
            isValidation = phoneValidator.validate(authRequest);
        }
        if("wechat".equals(authRequest.getCredenceType()) || "qq".equals(authRequest.getCredenceType())) {
            isValidation = socialValidator.validate(authRequest);
        }
        if(isValidation) {
            final String randomKey = jwtTokenUtil.getRandomKey();
            String userId = String.valueOf(userLoginDao.getUserIdByCredential(authRequest.getCredenceName(),MD5Util.encrypt(authRequest.getCredenceCode()),authRequest.getCredenceType()));
            final String token = jwtTokenUtil.generateToken(userId, randomKey);
            return ServerResponse.getSuccess("success",new AuthResponse(token,randomKey));
        } else {
            throw new BussinessException(BizExceptionEnum.AUTH_REQUEST_ERROR);
        }
    }

    /**
     * 短信登录
     * @param phoneNum
     * @param code
     * @return
     */
    @RequestMapping(value = "/msgLogin",method = RequestMethod.POST)
    public ServerResponse phoneMsgLogin(@RequestParam(value = "phoneNum") String phoneNum,
                                        @RequestParam(value = "code") String code) {
        String cacheCode = MsgCacheUtil.getKey(MsgType.LOGIN_TYPE.getTypePrefix()+phoneNum);
        if(StringUtils.isBlank(cacheCode)) {
            return ServerResponse.getErrorMessage("验证码已过期");
        }
        if(!cacheCode.equals(code)) {
            return ServerResponse.getErrorMessage("验证码错误");
        }
        Integer userId = msgValidator.getUserIdByPhoneNum(phoneNum);
        if(userId == null) {
            return ServerResponse.getErrorMessage("该用户不存在");
        }
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(String.valueOf(userId), randomKey);
        return ServerResponse.getSuccess("success",new AuthResponse(token,randomKey));
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param password
     * @return
     */
    @RequestMapping(value = "/user/updatePwd")
    public ServerResponse updatePwd(@RequestParam(value = "oldPassword") String oldPassword,
                                    @RequestParam(value = "password") String password) {
        if(password.length() < 6 || password.length() > 20) {
            return ServerResponse.getErrorMessage("密码不符合要求");
        }
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        //1.校验旧密码
        boolean checkResult = userService.checkOldPassword(userId,oldPassword);
        if(!checkResult) {
            return ServerResponse.getErrorMessage("原密码错误");
        }
        //2.修改用户密码
        userService.updatePwdByUserId(userId,password);
        return ServerResponse.getSuccess("修改成功");
    }

    /**
     * 得到用户信息
     * @return
     */
    @RequestMapping(value = "/user/info",method = RequestMethod.POST)
    public ServerResponse getUserInfo() {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        AppUser user = appUserMapper.selectById(userId);
        if(StringUtils.isBlank(user.getAvatar())) {
            user.setAvatar("");
        } else {
            String avatarUrl = user.getAvatar();
            user.setAvatar(addTokenUrl(avatarUrl));
        }
        if(StringUtils.isBlank(user.getNickName())) {
            user.setNickName("");
        }
        if(StringUtils.isBlank(user.getPhone())) {
            user.setPhone("");
        }
        return ServerResponse.getSuccess("success",user);
    }

    /**
     * 更新用户信息
     * @param content
     * @param type
     * @return
     */
    @RequestMapping(value = "/user/update",method = RequestMethod.POST)
    public ServerResponse bindPhoneForSocail(@RequestParam(value = "content") String content,
                                             @RequestParam(value = "type") String type) {
        if(StringUtils.isBlank(type)) {
            return ServerResponse.getErrorMessage("参数传递有误");
        }
        if("phone".equals(type)) {
            if(StringUtils.isBlank(content)) {
                log.error("手机号为空");
                return ServerResponse.getErrorMessage("手机号不能为空");
            }
            if(!RegExpValidatorUtil.isHandset(content)) {
                log.error("手机号不符合要求");
                return ServerResponse.getErrorMessage("手机号不符合要求");
            }
        } else {
            if(StringUtils.isBlank(content)) {
                log.error("修改内容不能为空");
                return ServerResponse.getErrorMessage("修改内容不能为空");
            }
        }

        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        return userService.updateUser(userId,content,type);
    }

    /**
     * 更新用户头像
     * @param avatar
     * @return
     * @throws IOException
     * @throws UpException
     */
    @RequestMapping(value = "/user/updateAvatar",method = RequestMethod.POST)
    public ServerResponse updateAvatar(@RequestPart("avatar") MultipartFile avatar) throws IOException, UpException {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        String filenameExtension = avatar.getOriginalFilename().substring(avatar.getOriginalFilename().lastIndexOf("."), avatar.getOriginalFilename().length());
        InputStream content = avatar.getInputStream();
        String pictureAddr = upyunService.uploadFile(content,filenameExtension);
        //将头像的url保存到对应的用户中
        userService.updateUserAvatar(userId,UriUtil.getUri(pictureAddr));
        pictureAddr = addTokenUrl(UriUtil.getUri(pictureAddr));
        Map<String,String> result = new HashMap<String,String>();
        result.put("avatarUrl",pictureAddr);
        return ServerResponse.getSuccess("update success",result);
    }

    /**
     * 得到用户所有的收藏夹
     * @return
     */
    @RequestMapping(value = "/user/allSongList",method = RequestMethod.POST)
    public ServerResponse findAllSongList() {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        List<SongList> songListList = songListDao.getSongListForUser(userId);
        songListList.parallelStream().forEach(songList -> {
            if(StringUtils.isNotBlank(songList.getLogoPath())) {
                songList.setLogoPath(addTokenUrl(songList.getLogoPath()));
            }
        });
        return ServerResponse.getSuccess("success",songListList);
    }

    /**
     * 创建用户收藏歌单
     * @return
     */
    @RequestMapping(value = "/user/createSongList",method = RequestMethod.POST)
    public ServerResponse createSongWishList(@RequestParam(value = "songListName") String songListName) {
        if(StringUtils.isBlank(songListName)) {
            return ServerResponse.getErrorMessage("收藏夹名称不能为空");
        }
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        return userService.createSongList(userId,songListName);
    }

    /**
     * 更新收藏夹名称
     * @param songListId
     * @param songListName
     * @return
     */
    @RequestMapping(value = "/user/updateSongListName",method = RequestMethod.POST)
    public ServerResponse updateSongListName(@RequestParam("songListId") Integer songListId,
                                             @RequestParam("songListName") String songListName) {
        if(songListId == null) {
            return ServerResponse.getErrorMessage("参数不能为空");
        }
        if(StringUtils.isBlank(songListName)) {
            return ServerResponse.getErrorMessage("收藏夹名称不能为空");
        }
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        return userService.updateSongList(userId,songListId,songListName);
    }

    /**
     * 删除用户收藏夹
     * @param songListId
     * @return
     */
    @RequestMapping(value = "/user/deleteSongList",method = RequestMethod.POST)
    public ServerResponse deleteSongList(@RequestParam(value = "songListId") Integer songListId) {
        if(songListId == null) {
            return ServerResponse.getErrorMessage("未能获取收藏夹id");
        }
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("获取用户信息失败");
        }
        return userService.deleteSongList(userId,songListId);
    }

    /**
     * 得到一个收藏夹下所有视频(分页)
     * @param currentPage
     * @param pageSize
     * @param songListId
     * @return
     */
    @RequestMapping(value = "/user/allSongListDetail",method = RequestMethod.POST)
    public ServerResponse allSongListDetail(@RequestParam(value = "currentPage",required = false) Integer currentPage,
                                            @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                            @RequestParam(value = "songListId") Integer songListId) {
        currentPage = currentPage == null ? 1 : currentPage;
        pageSize = pageSize == null ? 6 : pageSize;
        if(songListId == null) {
            return ServerResponse.getErrorMessage("收藏夹id不能为空");
        }
        return userService.songListDetail(currentPage,pageSize,songListId);
    }

    /**
     * 将一个视频收藏到收藏夹中
     * @param songListId
     * @param vedioId
     * @return
     */
    @RequestMapping(value = "/user/addVideoToSongList")
    public ServerResponse addVideoToSongList(@RequestParam(value = "songListId") Integer songListId,
                                             @RequestParam(value = "vedioId") Integer vedioId) {
        if(songListId == null || vedioId == null) {
            return ServerResponse.getErrorMessage("参数不能为空");
        }
        return userService.addVedioToSongList(songListId,vedioId);
    }

    /**
     * 将一个视频从收藏夹中删除
     * @param songListId
     * @param vedioId
     * @return
     */
    @RequestMapping(value = "/user/delVedioFromSongList",method = RequestMethod.POST)
    public ServerResponse deleteVedioFromSongList(@RequestParam(value = "songListId") Integer songListId,
                                                  @RequestParam(value = "vedioId") Integer vedioId) {
        if(songListId == null || vedioId == null) {
            return ServerResponse.getErrorMessage("参数不能为空");
        }
        return userService.deleteVideoFromSongList(songListId,vedioId);
    }

    /**
     * 更新token，主要是在用户启动进行更新
     * @return
     */
    @RequestMapping(value = "/user/updateToken",method = RequestMethod.POST)
    public ServerResponse updateUserToken() {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(String.valueOf(userId), randomKey);
        return ServerResponse.getSuccess("success",new AuthResponse(token,randomKey));
    }

    //*************************用户收藏视频模块（将用户与视频直接绑定，不再有收藏夹）****************//

    /**
     * 得到用户收藏的视频分页列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/user/pageUserVideo",method = RequestMethod.POST)
    public ServerResponse pageUserVideoList(@RequestParam(value = "currentPage",required = false) Integer currentPage,
                                            @RequestParam(value = "pageSize",required = false) Integer pageSize) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        currentPage = currentPage != null ? currentPage : 1;
        pageSize = pageSize != null ? pageSize : 6;
        return userService.userVideoList(currentPage,pageSize,userId,1);
    }

    /**
     * 得到用户收藏的音频分页列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/user/pageUserRadio",method = RequestMethod.GET)
    public ServerResponse pageUserRadioList(@RequestParam(value = "currentPage",required = false) Integer currentPage,
                                            @RequestParam(value = "pageSize",required = false) Integer pageSize) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        currentPage = currentPage != null ? currentPage : 1;
        pageSize = pageSize != null ? pageSize : 6;
        return userService.userVideoList(currentPage,pageSize,userId,0);
    }

    /**
     * 用户收藏视频
     * @param videoId
     * @return
     */
    @RequestMapping(value = "/user/userCollectVideo",method = RequestMethod.POST)
    public ServerResponse userCollectVideo(@RequestParam(value = "videoId") Integer videoId) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        return userService.userCollectVideo(userId,videoId);
    }

    /**
     * 用户删除收藏的视频
     * @param videoId
     * @return
     */
    @RequestMapping(value = "/user/userDeleteVideo",method = RequestMethod.POST)
    public ServerResponse userDeleteVideo(@RequestParam(value = "videoId") Integer videoId) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        return userService.userDeleteVideo(userId,videoId);
    }

    /**
     * 用户批量删除收藏的视频
     * @param videoIds
     * @return
     */
    @RequestMapping(value = "/user/userBatchDelVideo",method = RequestMethod.POST)
    public ServerResponse userBatchDelVideo(@RequestParam(value = "videoIds") String videoIds) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        String[] ids = videoIds.split(",");
        List<Integer> videoIdList = new ArrayList<Integer>();
        for (String id : ids) {
            videoIdList.add(Integer.valueOf(id));
        }
        return userService.userBatchDelVideo(userId,videoIdList);
    }

    /**
     * 用户是否收藏过该视频
     * @param videoId
     * @return
     */
    @RequestMapping(value = "/user/videoIsCollected",method = RequestMethod.POST)
    public ServerResponse isCollectVideo(@RequestParam(value = "videoId") Integer videoId) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        return userService.isCollectVideo(userId,videoId);
    }


    /**
     * 播放记录列表
     * @param currentPage
     * @param pageSize
     * @param resType 0音频，1视频
     * @return
     */
    @RequestMapping(value = "/user/play/record/list",method = RequestMethod.GET)
    public ServerResponse playRecordPageList(@RequestParam(value = "currentPage",required = false) Integer currentPage,
                                             @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                             @RequestParam(value = "resType") Integer resType) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }

        if(resType != 0 && resType != 1) {
            return ServerResponse.getErrorMessage("参数错误");
        }

        currentPage = currentPage != null ? currentPage : 1;
        pageSize = pageSize != null ? pageSize : 6;
        return ServerResponse.getSuccess("success",userService.userPlayRecordList(currentPage,pageSize,userId,resType));
    }

    /**
     * 清除播放记录
     * @param resourceIds
     * @return
     */
    @RequestMapping(value = "/user/play/record/clear",method = RequestMethod.POST)
    public ServerResponse batchDelPlayRecord(@RequestBody List<Integer> resourceIds) {
        Integer userId = getUserId();
        if(userId == null) {
            return ServerResponse.getErrorMessage("token已过期，无法更新");
        }
        userService.delPlayRecord(resourceIds,userId);
        return ServerResponse.getSuccess("清除成功");
    }

    /**
     * 通过jwt得到userId
     * @return
     */
    private Integer getUserId() {
        HttpServletRequest request = super.getHttpServletRequest();
        final String requestHeader = request.getHeader(jwtProperties.getHeader());
        String authToken = null;
        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            authToken = requestHeader.substring(7);
            Integer userId = Integer.valueOf(jwtTokenUtil.getUsernameFromToken(authToken));
            return userId;
        } else {
            return null;
        }
    }

    /**
     * 对url添加token,防止盗链
     * @param url
     * @return
     */
    private String addTokenUrl(String url) {
        return upyunProperties.getDomain() + url + "?_upt=" + upyunService.getTokenSign(UriUtil.getUri(url),EXPIRE_TIME);
    }
}

